package com.aloda.tools;

import com.aloda.constant.RedisConstant;
import com.aloda.dto.UserSafetyDTO;
import com.aloda.entity.User;
import com.google.gson.Gson;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 一些redis的操作工具
 *
 * @author aloda
 */
public class RedisOperateUtils {

    /**
     * 向redis中保存user
     * @param user 用户
     * @param token token
     * @param stringRedisTemplate stringRedisTemplate
     */
    public static void saveUserInRedis(User user, String token, StringRedisTemplate stringRedisTemplate) {
        UserSafetyDTO userSafetyDTO = UserSafetyDTO.builder()
                .id(user.getId())
                .userAccount(user.getUserAccount())
                .phone(user.getPhone())
                .build();
        Gson gson = new Gson();
        String userJson = gson.toJson(userSafetyDTO);
        stringRedisTemplate.opsForValue().set(RedisConstant.USER_TOKEN_KEY + token, userJson, RedisConstant.USER_TOKEN_TIMEOUT, TimeUnit.MINUTES);
    }

    /**
     * 从redis中获取用户
     * @param token token
     * @param stringRedisTemplate stringRedisTemplate
     * @return 用户安全类
     */
    public static UserSafetyDTO getUserInRedis(String token, StringRedisTemplate stringRedisTemplate) {
        String userSafetyInfo = stringRedisTemplate.opsForValue().get(RedisConstant.USER_TOKEN_KEY + token);
        if (userSafetyInfo == null || userSafetyInfo.isEmpty()) {
            return null;
        }
        Gson gson = new Gson();
        return gson.fromJson(userSafetyInfo, UserSafetyDTO.class);
    }

    /**
     * 从Redis中删除用户
     * @param token token
     * @param stringRedisTemplate stringRedisTemplate
     * @return true-删除成功 false-删除失败
     */
    public static Boolean deleteUserInRedis(String token, StringRedisTemplate stringRedisTemplate) {
        return stringRedisTemplate.delete(RedisConstant.USER_TOKEN_KEY + token);
    }
}
